package com.anpy.bill.service.impl;

import cn.hutool.json.JSONUtil;
import com.anpy.bill.mapper.UserMapper;
import com.anpy.bill.model.Constants;
import com.anpy.bill.model.param.AccountLoginParam;
import com.anpy.bill.model.result.AccountLoginResult;
import com.anpy.bill.model.result.LoginResult;
import com.anpy.bill.service.LoginService;
import com.anpy.bill.service.TokenService;
import com.anpy.common.service.utils.RedisUtils;
import com.anpy.personal.BaseException;
import com.anpy.personal.CommonResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.personal.dao.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @Description: 登录业务实现类
 * @Author: anpy
 * @date: 2025/4/7 10:13
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private TokenService tokenService;
    @Resource
    private UserMapper userMapper;

    /**
     * 登录失败重试时间
     */
    @Value("${error.password.wait.time:600}")
    private int errorPasswordWaitTime;



    /**
     * 账号密码登录
     *
     * @param param   account: 账号
     *                password: 密码
     */
    @Override
    public LoginResult accountLogin(AccountLoginParam param) {

        // 验证账号密码
        UserEntity user = authenticateUser(param);

        // 清除登录失败记录
//        RedisUtils.delete(Constants.LOGIN_ERROR_COUNT + param.getAccount());

        // 生成 token
        String token = tokenService.generateToken(user);

        // 返回登录结果
        return LoginResult.builder()
                .id(user.getId())
                .userName(user.getUserName())
                .token(token)
                .build();
    }

    /**
     * 验证账号密码
     */
    private UserEntity authenticateUser(AccountLoginParam param) {
        UserEntity userEntity = userMapper.selectOne(new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getPhone, param.getAccount())
                .eq(UserEntity::getPassword, param.getPassword()));
        if(userEntity == null){
            CommonResponse.assertError("账号密码错误");
        }

        return userEntity;
    }

    @Override
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        // 禁止图像缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 创建验证码对象
        int width = 100; // 验证码图片宽度
        int height = 40; // 验证码图片高度
        int codeCount = 4; // 验证码字符数
        int lineCount = 20; // 干扰线数量

        // 创建图像缓冲区
        BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffImg.createGraphics();

        // 创建一个随机数生成器
        Random random = new Random();

        // 设置图像背景
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 创建字体
        Font font = new Font("Fixedsys", Font.BOLD, 24);
        g.setFont(font);

        // 画边框
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width - 1, height - 1);

        // 随机产生干扰线
        g.setColor(Color.BLACK);
        for (int i = 0; i < lineCount; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(width);
            int yl = random.nextInt(height);
            g.drawLine(x, y, x + xl, y + yl);
        }

        // 生成随机验证码
        StringBuilder randomCode = new StringBuilder();
        // 验证码字符集
        String chars = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789";

        // 随机产生验证码字符
        for (int i = 0; i < codeCount; i++) {
            // 得到随机字符
            char c = chars.charAt(random.nextInt(chars.length()));
            // 将随机字符加入到验证码中
            randomCode.append(c);
            // 用随机颜色画验证码字符
            g.setColor(new Color(random.nextInt(100), random.nextInt(100), random.nextInt(100)));
            g.drawString(String.valueOf(c), (i * 20) + 15, 25);
        }

        // 将验证码存入session
        request.getSession().setAttribute("randomCode", randomCode.toString());

        // 释放图形上下文
        g.dispose();

        // 输出图像到页面
        OutputStream sos = response.getOutputStream();
        ImageIO.write(buffImg, "jpeg", sos);
        sos.close();
    }
}
